package com.cybertooth.dbconvenience.query.conditions;

import com.cybertooth.dbconvenience.query.core.SqlTransformer;
import com.cybertooth.dbconvenience.query.enums.LogicalOperator;
import com.cybertooth.dbconvenience.query.functions.SqlTransformerFunction;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

import java.util.Deque;

/**
 * <p></p>
 *
 * @author dnelson
 */
public class ConditionGroup implements SqlTransformer, SingleLogicalOperator<ConditionGroup> {

	// -----------------------------------------------------------------------Fields

	protected Deque<SqlTransformer> conditionParts;

	// -----------------------------------------------------------------Constructors

	public static ConditionGroup group(ColumnCondition columnCondition) {
		return new ConditionGroup(columnCondition);
	}

	private ConditionGroup(ColumnCondition columnCondition) {
		this.conditionParts = Lists.newLinkedList();
		this.conditionParts.push(columnCondition);
	}

	// ---------------------------------------------------------------Public Methods

	@Override
	public ConditionGroup not(ColumnCondition columnCondition) {
		this.conditionParts.push(LogicalOperator.NOT);
		this.conditionParts.push(columnCondition);
		return this;
	}

	@Override
	public ConditionGroup and(ColumnCondition columnCondition) {
		this.conditionParts.push(LogicalOperator.AND);
		this.conditionParts.push(columnCondition);
		return this;
	}

	@Override
	public ConditionGroup or(ColumnCondition columnCondition) {
		this.conditionParts.push(LogicalOperator.OR);
		this.conditionParts.push(columnCondition);
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String toSql() {
		return new StringBuilder()
				.append(" (")
				.append(Joiner.on("").join(Iterables.transform(this.conditionParts, new SqlTransformerFunction())))
				.append(") ")
				.toString();
	}
}
